import { showNotify, showConfirmDialog } from "vant";
import { getToken, getWeappToken } from "../utils/auth";
import axios from "axios";
import errorCode from "../utils/errorCode";
import router from "../router/index";
import { clearUserInfo } from "../utils/common";
import { ElMessage } from "element-plus";
import { commonStore } from "../stores/common";
import { storeToRefs, createPinia } from "pinia";

const pinia = createPinia();
const store = commonStore(pinia);
const { isMobile } = storeToRefs(store);

// 报错提示
const msgError = (msg) => {
  if (isMobile.value) {
    showNotify({ type: "danger", message: msg });
  } else {
    ElMessage.error(msg);
  }
};

let timeout = 10000;
const http = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API, // api base_url
  timeout: timeout,
  withCredentials: true,
  headers: {
    "Content-Type": "application/json; charset=utf-8"
  }
});

/*
 * 请求拦截
 */
http.interceptors.request.use(
  (config) => {
    let cookie = getToken();
    let weappToken = getWeappToken();
    if (cookie) config.headers["Authorization"] = "Bearer " + cookie;
    if (weappToken) config.headers["token"] = "Zhgh " + weappToken;
    config.headers["x-referer"] = "Zhgh";
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

/**
 * 响应拦截
 */
http.interceptors.response.use(
  (response) => {
    let res = response;
    const code = res.data.code || 200;
    const msg = errorCode[code] || res.data.msg || errorCode["default"];
    if (code === 401) {
      showConfirmDialog({
        message: "登录状态已过期，您可以继续留在该页面，或者重新登录?"
      }).then(() => {
        clearUserInfo();
        router.replace({
          name: "Login",
          query: { from: router.currentRoute.value.fullPath }
        });
      });
      return Promise.reject("无效的会话，或者会话已过期，请重新登录。");
    } else if (code === 500) {
      msgError(msg);
      return Promise.reject("500");
    } else if (code !== 200) {
      msgError(msg);
      return Promise.reject(code);
    }
    return response.data;
  },
  (error) => {
    let { message } = error;
    if (message === "Network Error") {
      message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    msgError(message);
    return Promise.reject(error);
  }
);
export default http;
